import { getper, getrole, postRole , removeRole } from '../../api/permission'
import { constantRoutes, asyncRouter } from "../../router/index"
export default {
    namespaced: true,
    state: {
        roleArr: [],
        routes: []
    },
    mutations: {
        SET_ROLEARR(state, res) {
            res.map(v => {
                if (!v.items) {
                    v.items = []
                } else {
                    v.items = JSON.parse(v.items)
                }
            })
            state.roleArr = res
        },
        SET_ROUTES(state, res) {
            state.routes = [...constantRoutes, ...res]
        }
    },
    actions: {
        // 获取权限
        async getper({ commit }, res) {
            let r = await getper()
            commit("SET_ROLEARR", r.data)
        },
        // 拿到角色
        async getRoles({ commit }, res) {
            let r = await getrole({ roles: res[0] })
            let item = r.data[0]
            let rolesArr = JSON.parse(item.items)
            let asyncrouters = []
            if (res[0] == 'admin') {
                asyncrouters = asyncRouter
                commit("SET_ROUTES", asyncRouter)
            } else {
                let asyncroute = filterRou(res[0], asyncRouter, rolesArr)
                asyncrouters = asyncroute
                commit("SET_ROUTES", asyncroute)
            }

            return asyncrouters
        },
        // 新增  修改  角色
        async postRole({ commit, dispatch }, res) {
            let r = await postRole(res)
            dispatch("getper")
        },
        // 删除角色
        async removeRole({dispatch},id){
            let r = await removeRole(id)
            dispatch("getper")
        }
    }
}


// 用权限过滤
function filterRou(roles, routerArr, roleArr) {
    const res = []
    routerArr.forEach(v => {
        let tmp = { ...v }
        if (hasRoles(tmp, roles, roleArr)) {  // 看路由是否跟当前角色相匹配
            if (tmp.children) {
                tmp.children = filterRou(roles, tmp.children, roleArr)
            }
            res.push(tmp)
        }
    });
    return res
}

function hasRoles(a, role, roleArr) {
    if (a.children && a.children.length == 1) {
        return roleArr.includes(a.children[0].meta.title)
    } else if (!a.children) {
        return roleArr.includes(a.meta.title)
    } else {
        let isShow = a.children.some(v => {
            return roleArr.includes(v.meta.title)
        })
        return isShow
    }
}
